package com.ocom.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.noticeBoard.EntityNoticeBoardInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetNoticeBoardListRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.company.GetNoticeBoardByComVo;
import com.ocom.company.dao.IDaoNoticeBoard;
import com.ocom.company.service.CompanyListInfoService;
import com.ocom.company.service.NoticeBoardService;
import com.ocom.company.vo.HomeNoticeVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NoticeBoardServiceImpl extends ServiceImpl<IDaoNoticeBoard, EntityNoticeBoardInfo> implements NoticeBoardService {

    @Autowired
    IDaoNoticeBoard iDaoNoticeBoard;

    @Autowired
    private CompanyListInfoService companyListInfoService;

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public PageInfo<EntityNoticeBoardInfo> getNoticeBoardList(GetNoticeBoardListRequest requestData) {
        QueryWrapper<EntityNoticeBoardInfo> queryWrapper = new QueryWrapper<>();

        // 添加条件
        if (requestData.getComId() != null && requestData.getComId() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("com_ids")
                            .or()
                            .eq("com_ids", "")
                            .or()
                            .apply("FIND_IN_SET({0}, com_ids) > 0", requestData.getComId())
            );
        }
        if (requestData.getAgentId() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("agent_ids")
                            .or()
                            .eq("agent_ids", "")
                            .or()
                            .apply("FIND_IN_SET({0}, agent_ids) > 0", requestData.getAgentId())
            );
        }
        if (requestData.getSaasId() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("saas_ids")
                            .or()
                            .eq("saas_ids", "")
                            .or()
                            .apply("FIND_IN_SET({0}, saas_ids) > 0", requestData.getSaasId())
            );
        }

        if (requestData.getMjVer() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("mj_vers")
                            .or()
                            .eq("mj_vers", "")
                            .or()
                            .apply("FIND_IN_SET({0}, mj_vers) > 0", requestData.getMjVer())
            );
        }

        if (requestData.getXfVer() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("xf_vers")
                            .or()
                            .eq("xf_vers", "")
                            .or()
                            .apply("FIND_IN_SET({0}, xf_vers) > 0", requestData.getXfVer())
            );
        }

        if (requestData.getRoleId() > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("role_ids")
                            .or()
                            .eq("role_ids", "")
                            .or()
                            .apply("FIND_IN_SET({0}, role_ids) > 0", requestData.getRoleId())
            );
        }

        // 添加模糊查询条件
        if (StringUtils.isNotBlank(requestData.getTitle())) {
            queryWrapper.like("title", "%" + requestData.getTitle() + "%");
        }

        // 添加时间范围条件
        if (requestData.getBeginTime() != null) {
            // 结束时间大于或等于 开始时间
            queryWrapper.ge("end_time", requestData.getBeginTime());
        }
        if (requestData.getEndTime() != null) {
            // 开始时间小于或等于 结束时间
            queryWrapper.le("begin_time", requestData.getEndTime());
        }

        // 排序和分页
        queryWrapper.orderByDesc("sort", "begin_time");
        PageHelper.startPage(requestData.getPage(), requestData.getSize());
        List<EntityNoticeBoardInfo> list = this.list(queryWrapper);
        PageInfo<EntityNoticeBoardInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public Result addNoticeBoard(EntityNoticeBoardInfo entityNoticeBoardInfo) {
        if (entityNoticeBoardInfo.getBeginTime() == null) {
            return ResultUtil.info(203, "公告开始时间为空");
        }
        if (entityNoticeBoardInfo.getEndTime() == null) {
            return ResultUtil.info(203, "公告结束时间为空");
        }
        if (StringUtils.isEmpty(entityNoticeBoardInfo.getTitle())) {
            return ResultUtil.info(203, "公告标题为空");
        }
        if (StringUtils.isEmpty(entityNoticeBoardInfo.getContent())) {
            return ResultUtil.info(203, "公告内容富文本为空");
        }
        if (entityNoticeBoardInfo.getSort() == null) {
            return ResultUtil.info(203, "排序号不能为空");
        }
        int insert = iDaoNoticeBoard.insert(entityNoticeBoardInfo);
        if (insert > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.Err_2009);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public Result updateNoticeBoard(EntityNoticeBoardInfo entityNoticeBoardInfo) {
        if (entityNoticeBoardInfo.getId() == null || entityNoticeBoardInfo.getId() < 0) {
            return ResultUtil.info(203, "公告编号ID为空");
        }
        if (entityNoticeBoardInfo.getBeginTime() == null) {
            return ResultUtil.info(203, "公告开始时间为空");
        }
        if (entityNoticeBoardInfo.getEndTime() == null) {
            return ResultUtil.info(203, "公告结束时间为空");
        }
        if (StringUtils.isEmpty(entityNoticeBoardInfo.getTitle())) {
            return ResultUtil.info(203, "公告标题为空");
        }
        if (StringUtils.isEmpty(entityNoticeBoardInfo.getContent())) {
            return ResultUtil.info(203, "公告内容富文本为空");
        }
        if (entityNoticeBoardInfo.getSort() == null) {
            return ResultUtil.info(203, "排序号不能为空");
        }
        int insert = iDaoNoticeBoard.updateById(entityNoticeBoardInfo);
        if (insert > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.Err_2009);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public Result deleteNoticeBoard(Long id) {
        if (id == null || id < 0) {
            return ResultUtil.info(203, "公告编号ID为空");
        }
        int i = iDaoNoticeBoard.deleteById(id);
        if (i > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.Err_2009);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB, isMaster = MasterSlaveEnum.SLAVE)
    public Result homeNoticeOnShow(Long comId) {
        QueryWrapper<EntityNoticeBoardInfo> queryWrapper = new QueryWrapper<>();
        // 添加条件
        if (comId != null && comId > 0) {
            queryWrapper.and(wrapper ->
                    wrapper.isNull("com_ids")
                            .or()
                            .eq("com_ids", "")
                            .or()
                            .apply("FIND_IN_SET({0}, com_ids) > 0", comId)
            );
        }
        // 排序
        queryWrapper.orderByDesc("update_time");
        List<EntityNoticeBoardInfo> list = this.list(queryWrapper);
        List<HomeNoticeVo> dataList = list.stream().map(entity -> new HomeNoticeVo(entity.getId(), entity.getTitle(), entity.getContent())).collect(Collectors.toList());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", dataList);
        return ResultUtil.success(hashMap);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.MAIN_DB, isMaster = MasterSlaveEnum.SLAVE)
    public List<EntityNoticeBoardInfo> getNoticeBoardByCom(Long comId, Long roleId) {

        Date date = new Date();
        EntityCompanyList companyInfo = this.companyListInfoService.GetCompanyListInfo(comId);
        QueryWrapper<EntityNoticeBoardInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("begin_time",date)
                .ge(" end_time",date)
                .and(wrapper->wrapper.isNull("com_ids").or().apply("FIND_IN_SET({0}, com_ids) > 0",comId))
                .and(wrapper->wrapper.isNull("agent_ids").or().apply("FIND_IN_SET({0}, agent_ids) > 0",companyInfo.getAgentId()))
                .and(wrapper->wrapper.isNull("saas_ids").or().apply("FIND_IN_SET({0}, saas_ids) > 0",companyInfo.getSaasId()))
                .and(wrapper->wrapper.isNull("mj_vers").or().apply("FIND_IN_SET({0}, mj_vers) > 0",companyInfo.getMjStatus()))
                .and(wrapper->wrapper.isNull("xf_vers").or().apply("FIND_IN_SET({0}, xf_vers) > 0",companyInfo.getXfStatus()))
                .and(wrapper->wrapper.isNull("role_ids").or().apply("FIND_IN_SET({0}, role_ids) > 0",roleId))
                .orderByDesc("sort","begin_time").last("limit 20")
        ;

        return  this.list(queryWrapper);
    }
}
